// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UdpFarProxy.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;

    /// <summary>
    /// A proxy acts as an intermediary between another agent host and some resource, in this case the network. 
    /// The far proxy takes the agent's place on a remote machine, acting on its behalf. 
    /// A far proxy is thus created in a different proc or different machine than the agent it represents.
    /// The far proxy reads from the network and broadcasts locally the messages published by the agent, and sends to the network any control messages targeting the agent.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Design",
    "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
    Justification = "PipelineElements clean up resources when OnDeactivated() is called")]
    internal class UdpFarProxy : PipelineElement
    {
        /// <summary>
        /// The definition of the proxy: agent name, pins to expose etc.
        /// </summary>
        private ProxyDefinition proxyDefinition;

        /// <summary>
        /// The name of this proxy
        /// </summary>
        private string name;

        /// <summary>
        /// The UDP sender to use for sending control messages.
        /// </summary>
        private UdpSender sender;

        /// <summary>
        /// The UDP listener to use for receiving messages published by the remote agent.
        /// </summary>
        private UdpListener listener;

        /// <summary>
        /// Initializes a new instance of the UdpFarProxy class. 
        /// </summary>
        /// <param name="proxyDefinition">The definition of the agent proxy.</param>
        /// <param name="locator">The locator to use for agent wiring.</param>
        internal UdpFarProxy(ProxyDefinition proxyDefinition, AgentLocator locator)
            : base(locator)
        {
            this.proxyDefinition = proxyDefinition;
            this.name = this.proxyDefinition.Name;
        }

        /// <summary>
        /// Gets the name of the wrapped agent instance.
        /// </summary>
        internal override string Name
        {
            get
            {
                return this.name;
            }
        }

        /// <summary>
        /// Creates the ports that act on behalf of the remote agent, and connects the udp listener/sender to the them.
        /// </summary>
        /// <param name="offlineMode">Not used.</param>
        /// <param name="pipelineCreationTime">The time when the locator was created. Used as the time origin for agent message timestamps</param>
        internal override void InitializePorts(bool offlineMode, long pipelineCreationTime)
        {
            base.InitializePorts(offlineMode, pipelineCreationTime);
            IPAddress[] addresses = Dns.GetHostAddresses(this.proxyDefinition.NetworkAddress);

            if (addresses == null || addresses.Length == 0)
            {
                throw new InvalidOperationException(
                    string.Format(
                        "The remote address {0} for proxy {1} could not be resolved.", 
                        this.proxyDefinition.NetworkAddress, 
                        this.proxyDefinition.Name));
            }

            IPAddress address = addresses.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).First();

            // create the broadcast ports
            if (this.proxyDefinition.PublishSet != null)
            {
                Dictionary<Type, IForwarder> publishers = new Dictionary<Type, IForwarder>();

                foreach (Type messageType in this.proxyDefinition.PublishSet.GetContracts())
                {
                    publishers[messageType] = this.AddPublishingPort(messageType);
                }

                // create the udp listener and hook it up to each control port
                this.listener = new UdpListener(this.proxyDefinition.PublishSet.Port, address, publishers, pipelineCreationTime);
            }

            // create the control ports
            if (this.proxyDefinition.ControlSet != null)
            {
                // set up the UDP sender
                IPEndPoint endpoint = new IPEndPoint(address, this.proxyDefinition.ControlSet.Port);
                IEnumerable<Type> types = this.proxyDefinition.ControlSet.GetContracts();
                this.sender = new UdpSender(endpoint, types);

                // create the control ports and hook them up to the sender
                foreach (Type type in types)
                {
                    this.AddControlPort(type, this.sender, false, 0);
                }
            }
        }

        /// <summary>
        /// Called to do our own activation before the control loop is started
        /// </summary>
        protected override void OnActivated()
        {
            if (this.listener != null)
            {
                this.listener.Start();
            }
        }

        /// <summary>
        /// Called to do our own cleanup right after the control loop is stopped. 
        /// </summary>
        protected override void OnDeactivated()
        {
            if (this.listener != null)
            {
                this.listener.Stop();
            }
        }
    }
}
